package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 今日佳人服务接口实现类
 */
@Service
public class RecommendUserApImpl implements RecommendUserApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据当前登录用户id查询今日佳人用户(缘分值最高 - 只匹配一个用户)
     * @param currentUserId
     * @return
     */
    @Override
    public RecommendUser findByUserId(Long currentUserId) {
        //构造查询条件  根据缘分值排序 倒序-1  limit 1条记录  toUserId=当前用户id
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(currentUserId));
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        query.limit(1);
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    /**
     * 推荐佳人分页列表数据
     */
    @Override
    public PageResult<RecommendUser> recommendation(Integer page, Integer pagesize, Long currentUserId) {
        //1.查询总记录数
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(currentUserId));//根据当前用户id 查询推荐用户列表数据
        long counts = mongoTemplate.count(query, RecommendUser.class);
        //2.查询当前页面需要展示的数据
        query.limit(pagesize).skip((page-1)*pagesize);
        //根据缘分值排序 将缘分值最高的放前面展示
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //3.封装数据返回
        Long pages = counts/pagesize + (counts%pagesize > 0 ? 1:0);
        return new PageResult<>(counts,(long)pagesize,pages,(long)page,recommendUserList);
    }

    /**
     * 获取缘分值
     * @param personUserId
     * @param userId
     * @return
     */
    @Override
    public Double findByUserIdAndPersonId(Long personUserId, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(personUserId).and("toUserId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser == null || recommendUser.getScore() == null){
            return 99.9d;
        }
        return recommendUser.getScore();
    }
}
